package org.maxkey.portal.core.util;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.SignedJWT;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.util.Date;

@Slf4j
public class JwtUtil {


    /**
     * 获取jwtToken的认证用户
     * @param publicRsaKey 公钥
     * @param token token
     * @return
     */
    public static String getAccessIssuer(String publicRsaKey,String token){
        try {
            SignedJWT jwt = SignedJWT.parse(token);
            //添加私密钥匙 进行解密
            RSASSAVerifier rsassaVerifier = new RSASSAVerifier(RSAKey.parse(publicRsaKey));
            //校验是否有效
            if (!jwt.verify(rsassaVerifier)) {
                log.error("Token 无效:{}",token);
                return null;
            }
            //校验超时
            if (new Date().after(jwt.getJWTClaimsSet().getExpirationTime())) {
                log.error("Token 已过期:{}",token);
                return null;
            }
            //获取载体中的数据
            return jwt.getJWTClaimsSet().getIssuer();
        }catch (ParseException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        }
        return null;
    }
}
